Hi!
So i followed this video: https://www.youtube.com/watch?v=HBirbA5-xiA
And since i'm yet no Go expert by far, I want to avoid any framework or library for the time being, just learn all around without any "help" kind of approach, yet I found myself needing GorillaMux for my current code:
package main
import (
"crypto/md5"
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
)
var urlStore = make(map[string]string)
func shorten(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
url := r.Form.Get("url")
shortURL := fmt.Sprintf("%x", md5.Sum([]byte(url)))[:5]
urlStore[shortURL] = url
fmt.Fprintf(w, "http://localhost:8080/%s\n", shortURL)
}
func redirect(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
oUrl, ok := urlStore[vars["shortURL"]]
if ok {
http.Redirect(w, r, oUrl, http.StatusMovedPermanently)
} else {
http.NotFound(w, r)
}
}
func main() {
r := http.NewServeMux()
r.HandleFunc("POST /create", shorten)
r.HandleFunc("GET /{shortURL}", redirect)
log.Print("Starting server on port :8080...")
log.Fatal(http.ListenAndServe(":8080", r))
}
It is pretty much the same as the video shows but I did it to use net/http instead of mux, yet I found myself unable to remove the vars := mux.Vars(r) line, since I don't really understand what is he doing there, overall I get how this works yet it needs quite some comments and refinement imo, but the thing is, can i replace that line? If so, how? (let me know as in "you can define this or do that", not the code in on itself please
Lets build a URL shortener with Golang and Gorilla Mux
Learn to build real software projects on CodeCrafters
https://app.codecrafters.io/join?via=TheBuilder-software