Want to build a web server in Go? You’re in luck! Go’s built-in net/http
package makes it super easy to create blazing-fast web servers. Let’s dive into the world of HTTP servers with Go and start serving content like a boss!
Creating a Basic HTTP Server
With just a few lines of code, you can spin up a Go-powered web server. No frameworks, no nonsense—just Go magic!
Example: Hello, Go HTTP Server!
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, Gopher! You’ve reached my Go web server!")
}
func main() {
http.HandleFunc("/", handler)
fmt.Println("Server running on http://localhost:8080")
http.ListenAndServe(":8080", nil)
}
Output:
Open your browser and visit http://localhost:8080
. You’ll see:
Hello, Gopher! You’ve reached my Go web server!
Boom! You just built a server in less than 10 lines of code.
Handling Multiple Routes
A real server needs more than just one route. Let’s add multiple endpoints!
Example: Adding More Routes
package main
import (
"fmt"
"net/http"
)
func homeHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome to the Home Page!")
}
func aboutHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "This is the About Page!")
}
func main() {
http.HandleFunc("/", homeHandler)
http.HandleFunc("/about", aboutHandler)
fmt.Println("Server running on http://localhost:8080")
http.ListenAndServe(":8080", nil)
}
Now, visit /about
, and you’ll get a whole new page!
Serving Static Files
Want to serve CSS, JavaScript, or images? Easy!
Example: Serving Static Files
package main
import (
"net/http"
)
func main() {
fs := http.FileServer(http.Dir("./static"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
http.ListenAndServe(":8080", nil)
}
Just put your assets in the static/
folder, and Go will serve them automatically!
Handling Forms and Query Parameters
Forms and URL parameters are crucial for interactivity.
Example: Handling Form Data
package main
import (
"fmt"
"net/http"
)
func formHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
r.ParseForm()
name := r.FormValue("name")
fmt.Fprintf(w, "Hello, %s!", name)
}
}
func main() {
http.HandleFunc("/submit", formHandler)
fmt.Println("Server running on http://localhost:8080")
http.ListenAndServe(":8080", nil)
}
Now, when you submit a form to /submit
, Go will process it!
Go’s net/http
package makes building web servers ridiculously easy. Whether you're making a simple website or a full API, Go has your back. Now go forth and build something awesome!
0 Comments