Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse a url with # in GO

Tags:

http

request

go

So I'm receiving a request to my server that looks a little something like this

http://localhost:8080/#access_token=tokenhere&scope=scopeshere

and I can't seem to find a way to parse the token from the url.

If the # were a ? I could just parse it a standard query param.

I tried to just getting everything after the / and even the full URL, but with no luck.

Any help is greatly appreciated.

edit:

So I've solved the issue now, and the correct answer is you can't really do it in GO. So I made a simple package that will do it on the browser side and then send the token back to the server.

Check it out if you're trying to do local twitch API stuff in GO:

https://github.com/SimplySerenity/twitchOAuth

like image 955
SimplySerenity Avatar asked Aug 06 '17 22:08

SimplySerenity


2 Answers

Anchor part is not even (generally) sent by a client to the server.

Eg, browsers don't send it.

like image 141
zerkms Avatar answered Oct 19 '22 02:10

zerkms


For parse urls use the golang net/url package: https://golang.org/pkg/net/url/

OBS: You should use the Authorization header for send auth tokens.

Example code with extracted data from your example url:

package main

import (
  "fmt"
  "net"
  "net/url"
)

func main() {
    // Your url with hash
    s := "http://localhost:8080/#access_token=tokenhere&scope=scopeshere"
    // Parse the URL and ensure there are no errors.
    u, err := url.Parse(s)
    if err != nil {
        panic(err)
    }

    // ---> here is where you will get the url hash #
    fmt.Println(u.Fragment)
    fragments, _ := url.ParseQuery(u.Fragment)
    fmt.Println("Fragments:", fragments)
    if fragments["access_token"] != nil {
      fmt.Println("Access token:", fragments["access_token"][0])
    } else {
      fmt.Println("Access token not found")
    }


    // ---> Others data get from URL:
     fmt.Println("\n\nOther data:\n")
    // Accessing the scheme is straightforward.
    fmt.Println("Scheme:", u.Scheme)
    // The `Host` contains both the hostname and the port,
    // if present. Use `SplitHostPort` to extract them.
    fmt.Println("Host:", u.Host)
    host, port, _ := net.SplitHostPort(u.Host)
    fmt.Println("Host without port:", host)
    fmt.Println("Port:",port)
    // To get query params in a string of `k=v` format,
    // use `RawQuery`. You can also parse query params
    // into a map. The parsed query param maps are from
    // strings to slices of strings, so index into `[0]`
    // if you only want the first value.
    fmt.Println("Raw query:", u.RawQuery)
    m, _ := url.ParseQuery(u.RawQuery)
    fmt.Println(m)
}

// part of this code was get from: https://gobyexample.com/url-parsing
like image 39
Alberto Souza Avatar answered Oct 19 '22 00:10

Alberto Souza