Skip to content

Instantly share code, notes, and snippets.

@alyssaq
Last active February 13, 2024 08:01
Show Gist options
  • Save alyssaq/75d6678d00572d103106 to your computer and use it in GitHub Desktop.
Save alyssaq/75d6678d00572d103106 to your computer and use it in GitHub Desktop.
GET and POST golang API
/*
* Sample API with GET and POST endpoint.
* POST data is converted to string and saved in internal memory.
* GET endpoint returns all strings in an array.
*/
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
)
var (
// flagPort is the open port the application listens on
flagPort = flag.String("port", "9000", "Port to listen on")
)
var results []string
// GetHandler handles the index route
func GetHandler(w http.ResponseWriter, r *http.Request) {
jsonBody, err := json.Marshal(results)
if err != nil {
http.Error(w, "Error converting results to json",
http.StatusInternalServerError)
}
w.Write(jsonBody)
}
// PostHandler converts post request body to string
func PostHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, "Error reading request body",
http.StatusInternalServerError)
}
results = append(results, string(body))
fmt.Fprint(w, "POST done")
} else {
http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
}
}
func init() {
log.SetFlags(log.Lmicroseconds | log.Lshortfile)
flag.Parse()
}
func main() {
results = append(results, time.Now().Format(time.RFC3339))
mux := http.NewServeMux()
mux.HandleFunc("/", GetHandler)
mux.HandleFunc("/post", PostHandler)
log.Printf("listening on port %s", *flagPort)
log.Fatal(http.ListenAndServe(":"+*flagPort, mux))
}
@cnbbin
Copy link

cnbbin commented Jan 30, 2020

111

@cnbbin
Copy link

cnbbin commented Jan 30, 2020

111

@ogznglr
Copy link

ogznglr commented Jul 6, 2022

Useless bro. Post is a method it is not a part of URL. Client won't tell you whether he is using post or get method.

Copy link

ghost commented Dec 10, 2023

"The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line."
RFC 2616, § 9.5

POST is an HTTP method and should not be included as part of the URL endpoint.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment