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
+2.4k Unix/Linux : How to archive and compress entire directory ?
+4.7k Golang : Find age or leap age from date of birth example
+3.5k Golang : Qt Yes No and Quit message box example
+6.4k Golang : Rename directory
+2.9k Facebook : How to force facebook to scrape latest URL link data?
+2.2k Fix Google Analytics Redundant Hostnames problem
+1.6k Golang : Use NLP to get sentences for each paragraph example
+3.4k PHP : Shuffle to display different content or advertisement
+2.9k Javascript : Get operating system and browser information
+4.1k Golang : Get currencies exchange rates example
+4.3k Golang : Secure file deletion with wipe example
+1.7k Golang : How to check if a string with spaces in between is numeric?