Created
September 10, 2020 03:01
-
-
Save cho0o0/a03c0ad92c28024d8a09547ade3db0fd to your computer and use it in GitHub Desktop.
Golang Mock Server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io/ioutil" | |
"log" | |
"net/http" | |
) | |
func main() { | |
http.HandleFunc("/", handler) | |
fmt.Printf("Starting mock server powered by Golang on localhost:5050\n") | |
if err := http.ListenAndServe(":5050", nil); err != nil { | |
log.Fatal(err) | |
} | |
} | |
func handler(w http.ResponseWriter, r *http.Request) { | |
if r.URL.Path != "/" { | |
http.Error(w, "404 not found.", http.StatusNotFound) | |
return | |
} | |
switch r.Method { | |
case "GET": | |
w.WriteHeader(http.StatusOK) | |
_, _ = w.Write([]byte(`Called GET`)) | |
case "POST": | |
w.WriteHeader(http.StatusOK) | |
body, _ := ioutil.ReadAll(r.Body) | |
println(string(body)) | |
_, _ = w.Write(body) | |
default: | |
w.WriteHeader(http.StatusMethodNotAllowed) | |
_, _ = fmt.Fprintf(w, "Sorry, only GET and POST methods are supported.") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment