Golang : HTTP Server Example
Simple tutorial on HTTP server examples with Golang. Run the codes below and point your browser to http://localhost:8080
or http://localhost:8080/replyname/yourname
for example 2.
Example 1:
package main
import (
"net/http"
)
func SayHelloWorld(w http.ResponseWriter, r *http.Request) {
html := "Hello"
html = html + " World"
w.Write([]byte(html))
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", SayHelloWorld)
http.ListenAndServe(":8080", mux)
}
Example 2:
package main
import (
"net/http"
"strings"
)
func SayHelloWorld(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
}
func ReplyName(w http.ResponseWriter, r *http.Request) {
URISegments := strings.Split(r.URL.Path, "/")
w.Write([]byte(URISegments[1]))
}
func main() {
// http.Handler
mux := http.NewServeMux()
mux.HandleFunc("/", SayHelloWorld)
mux.HandleFunc("/replyname", ReplyName)
http.ListenAndServe(":8080", mux)
}
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+6.8k Javascript : How to get JSON data from another website with JQuery or Ajax ?
+5.8k Golang : Compound interest over time example
+16.8k Golang : How to save log messages to file?
+7.3k Golang : How to stop user from directly running an executable file?
+10.4k Golang : ISO8601 Duration Parser example
+5.3k Golang : If else example and common mistake
+21.9k Golang : Print leading(padding) zero or spaces in fmt.Printf?
+13.8k Golang : Google Drive API upload and rename example
+26.5k Golang : Find files by extension
+31.3k Golang : How to convert(cast) string to IP address?
+10k Golang : How to check if a website is served via HTTPS