At the most basic, you can get a http page with a simple http.Get
response, err := http.Get("https://www.google.com")
This is good for testing, but not recommended for production as the default http.Get has a timeout of 0. ie, never timeout
http.Get will automatically follow status 30x redirects.
func main() {
resp, err := http.Get("http://localhost:8080")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(body))
}
The more complex, but more powerful way is using http.Client, http.NewRequest, http.Client.Do
client := &http.Client {
Timeout: time.Second * 10,
}
req, err := http.NewRequest("GET", "https://jsonplaceholder.typicode.com/users", nil)
if err != nil {
log.Fatal(err)
}
resp, err := client.Do(req)
If you want to get the headers from a http.response, use it's Get() method
func getContentType(res *http.Response) {
headers := res.Header.Get("Content-Type")
fmt.Println(headers)
}
Typically used with creating or adding new data.
While there is a simple http.Post it's of limited use in production code. You can't set timeouts or add headers, so you should use http.NewRequest
jsonData, err := json.Marshal(commentStruct)
if err != nil {
return Comment{}, err
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
return data, err
}
req.Header.Set("Content-Type","application/json")
req.Header.Set("X-API-KEY", apiKey)
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
return data, err
}
defer res.Body.Close()
var comment Comment
decoder := json.NewDecoder(res.Body)
err = decoder.Decode(&comment)
Typically used to update data which is on the server.
PUT's are supposed to be idempotent, ie it's safe to make the same request more than once. POSTs are not idempotent.
eg, when adding a user, use POST. If you run it more than once, you are adding more than one user, which is generally an incorrect thing to do.
updating an existing user with a new phone number for example is idempotent, and so should use PUT. If you run it once or 5 times in a row, the end result is the same.
You could have it that PUT does create a new user if it doesn't exist, but if it does exist, it doesn't try to create an additional user. It just updates the existing one. That is still considered idempotent.
There is no http.Put, so you have to use http.NewRequest
A very basic http server. Works, but not recommended for production
func main() {
http.HandleFunc("/", viewHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
func viewHandler(w http.ResponseWriter, r *http.Request) {
placeholder := []byte("gagf")
_, err := w.Write(placeholder)
if err != nil {
log.Fatal(err)
}
}
const filepathRoot = "."
const port = "8080"
mux := http.NewServeMux()
srv := &http.Server{
Addr: ":" + port,
Handler: mux,
}
mux.Handle("/", http.FileServer(http.Dir(filepathRoot)))
log.Printf("Serving on port: %s\n", port)
log.Fatal(srv.ListenAndServe())
Parses URLs