Blog Articles

<

2 / 2

>
See Tags

Creating a basic HTTP server with Go

Go (or Golang) is a powerful and efficient programming language that excels in building scalable and concurrent applications. In this occasion, we'll walk through the process of creating a simple HTTP server using Go. By the end of this guide, you'll have a basic understanding of how to handle HTTP requests and responses. Today, I'm going to share what I've learnt so far about building an HTTP server wiht Go. ## Prerequisites Before we begin, make sure you have Go installed on your machine. You can download it from the official [Go website](https://go.dev/doc/install). ## Project Setup ```bash mkdir go-http-server cd go-http-server ``` Now, create a file named main.go for our Go code. ```go // main.go package main import ( "fmt" "net/http" ) func main() { // Your HTTP server code will go here } ``` ## Handling an HTTP Request To handle HTTP requests, we'll use the `http `package provided by Go. Let's create a simple HTTP handler function that responds to incoming requests. ```go import ( "errors" "fmt" "io" "net/http" "os" ) func get(w http.ResponseWriter, r *http.Request) { fmt.Printf("Responding to GET / /\n") io.WriteString(w, "Hello World!\n") } ``` Now, let's register this handler function in our HTTP server ```go func main() { http.HandleFunc("/", get) err := http.ListenAndServe(":8080", nil) if errors.Is(err, http.ErrServerClosed) { fmt.Printf("Server closed\n") } else if err != nil { fmt.Printf("Error starting server: %s\n", err) os.Exit(1) } } ``` ## Run Your HTTP Server Save the changes applied to main.go, and you can now run your HTTP server. ```bash go run main.go ``` Visit http://localhost:8080 in your web browser, and you should see the message "Hello World!". You can also use the curl command in cmd and you'll also get the same response ```bash curl http://localhost:8080/ ``` And that's it! You have your first HTTP server built with Go. You can expand it a bit further by using `mux` to multiplex a server and http.Handler implementation by `net/http` package, which you can use for a case like this. ```go package main import ( "encoding/json" "errors" "fmt" "math/rand" "net/http" "os" ) type User struct { ID string `json:"id"` Name string `json:"name"` } var users map[string]User var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") func generateId(n int) string { b := make([]rune, n) for i := range b { b[i] = letterRunes[rand.Intn(len(letterRunes))] } return string(b) } func getUsers(w http.ResponseWriter, r *http.Request) { fmt.Printf("Responding to GET /\n") usersList := make([]User, 0, len(users)) for _, user := range users { usersList = append(usersList, user) } res, err := json.Marshal(usersList) if err != nil { http.Error(w, "Internal Server Error", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) w.Write(res) } func createUser(w http.ResponseWriter, r *http.Request) { fmt.Printf("Responding to POST /") var newUser User decoder := json.NewDecoder(r.Body) err := decoder.Decode(&newUser) if err != nil { http.Error(w, "Bad Request", http.StatusBadRequest) return } newUser.ID = generateId(12) users[newUser.ID] = newUser res, err := json.Marshal(newUser) if err != nil { http.Error(w, "Internal Server Error", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) w.Write(res) } func main() { users = make(map[string]User) mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodGet: getUsers(w, r) case http.MethodPost: createUser(w, r) } }) err := http.ListenAndServe(":8080", mux) if errors.Is(err, http.ErrServerClosed) { fmt.Printf("Server closed") } else if err != nil { fmt.Printf("Error starting server: %s\n", err) os.Exit(1) } } ```

Google Developer Groups Surabaya: Developer Festival 2023

![GDG Surabaya Devfest 2023](https://drive.google.com/uc?export=view&id=1c89rcrXti_M3dUnHkIQIHnFR7e5MlWwc) DevFest Surabaya 2023 at the Yarra Ballroom was off the charts! Hanging out with Kusindra Aji Rabbany, Muhammad Fadhil Kholaf, Arsyad Ali Mahardika, Nico Lee N.H, Sulthan Budiman, and Muhammad Zuhair Zuhdi made the whole thing a blast. And guess what? Got to meet some cool SMK Telkom Malang alumni - Haidar Zamzam, Ronald Dimas Yuwandika, and Irfan Hakim. Small world, eh? The sessions were mind-blowing. We dived into some next-level projects, like Machine Learning and generative AI stuff. Seeing those concepts in action was like watching magics unfold. Prototyping AI in MakerSuit? That's some wild creativity meets tech genius thing right there. And oh, 'KerasNLP models' – I thought I'd get lost, but the speakers made it so damn clear. Natural Language Processing got a whole lot more interesting after that. I'm all hyped to play around with language and tech in my future projects. The session on making apps for different devices and screens with Kotlin and Compose Multiplatform? My mind are officially blown. Kotlin's versatility is no joke. I can't wait to dig deeper and see how I can use it in my own projects. But you know what made it even more awesome? The vibe. The whole place were buzzed with passion and excitement. Everyone was sharing ideas, working together – it was like a tech party, and I just happen to like tech a lot. As the day wrapped up, I felt pumped up and ready to rock. DevFest Surabaya 2023 didn't just level up my tech game; it sparked a fire in me. I'm taking all this cool stuff back to my projects, and I'm stoked to see how these innovations will shape my tech journey. Big shoutout to Google Developer Groups for throwing a fest that's not just about coding but about pushing boundaries and having a blast while doing it!

Vacation Journal: A Trip to Modangan Beach

The class graduation vacation on June 10, 2023, was a memorable experience as my classmates and I embarked on a trip to Modangan Beach in Malang, Indonesia. With its breathtaking beauty, the beach felt like a hidden paradise due to its relative obscurity. Our journey began at 5 a.m. when we gathered in Sawojajar, and around 5:30 a.m., we set off from Sawojajar towards Modangan Beach, which was approximately 75 kilometers away. We traveled by motorcycles, and the journey took about 4 to 5 hours. However, midway through the trip, two of our friends had a serious accident, which required us to halt temporarily and ensure they weren't severely injured. Thankfully, nobody was seriously hurt. Afterward, we finally arrived at the beach, and I was truly amazed by the breathtaking scenery it offered. The sky was a vibrant blue, and the sound of gentle waves, along with the clean and peaceful environment, made the beach truly feel like paradise. The views were phenomenal, and I took several photos to capture the moment. ![Pantai](https://res.cloudinary.com/dyw30vzvl/image/upload/v1688141468/IMG_20230610_095816_ywcizj.jpg) ![Pantai 2](https://res.cloudinary.com/dyw30vzvl/image/upload/v1688214376/blog/1688214363550-798.jpg) On our way back, we stopped by our friend Andi's house, which was conveniently close by, to rest for about 2 hours before continuing our journey home. During the trip, one of my friends and I accidentally got separated from the group and ended up getting lost for a while before eventually reuniting with the others. We finally arrived back in Sawojajar around 6 p.m. It was an exciting experience and a perfect way to conclude our best class farewell. This vacation created lasting memories and allowed us to bond even more closely. We feel grateful for the time we spent together at the stunning Modangan Beach. The entire trip enriched our experiences and created memories that will be cherished for a lifetime. It provided us with an opportunity to have fun, get to know each other better, and form unforgettable bonds.

Tenth Grade in Review

Something I've struggled with (and still struggle with) is reflecting on the previous year and wondering, "What did I even accomplish?" and "Did I truly make the most of my time?" and "Did I waste a whole year without any personal growth?" It is natural to feel stressed about unfinished tasks and easier to overlook the achievements made. Therefore, this year, I've decided to cultivate a habit of documenting my progress in one place, to prevent dismissing my own accomplishments. ### Personal Achievements One thing that has changed for sure is the place where I study, in 2021 I was a 9th-grader in [MTsN 3 Jakarta](https://mtsnegeri3jakarta.sch.id/) But starting from a year ago, I've been a student at [SMK Telkom Sandhy Putra Malang](https://smktelkom-mlg.sch.id/) majoring in Software Engineering. I've gained new friends, new teachers, and a completely new environment. <br /> ![SMK Telkom Malang](https://smktelkom-mlg.sch.id/assets/upload/galeri/1599633058_DSC06083.JPG) <br /> I've improved a lot here, from not even knowing how to print output in Java to building several projects with Java. Additionally, I've progressed from struggling with the easiest coding problems to successfully solving several challenging problems in [LeetCode](https://leetcode.com/). I've also developed some personal projects for fun, such as this small blogging platform. I've also learned a thing or two about time management (although I still struggle with it), and I've obtained several certificates from various learning platforms. So far, 10th grade has been the best year for me because I'm learning something that truly interests me. I hope that 11th grade will be just as fulfilling. ### Things That I Want to Improve One thing for sure that I need to improve is my money management skills. I tend to struggle with not buying things that I don't really need. Additionally, I'll make an effort to enhance my time management skills, as I still struggle with them. I also plan to adopt a proper study technique rather than simply memorizing everything for finals. Moreover, I'm determined to improve my programming and logical thinking skills as well. I'm also planning to dedicate myself to learning C++ seriously this year. I aim to read and complete 20 books this year. Here's a complete list on what I want to improve in 11th grade: 1. **Time management**: I aim to enhance my ability to prioritize tasks, set realistic goals, and allocate my time efficiently to achieve better life balance. 2. **Financial management**: I aspire to develop better money management skills like including budgeting, saving, and avoiding unnecessary expenses. 3. **Communication skills**: I intend to focus on improving my verbal and written communication skills, such as expressing ideas clearly, active listening, and effective collaboration. 4. **Health**: I'm committed to maintaining a healthy lifestyle by incorporating regular exercise, a balanced diet, and sufficient rest into my daily routine. 5. **Learning mindset**: I want to cultivate a growth mindset and embrace continuous learning. This includes expanding my knowledge, acquiring new skills, and seeking personal and professional development opportunities. 6. **Organization and productivity**: I aim to enhance my organizational skills, establish efficient systems, and improve productivity by eliminating distractions and implementing effective planning techniques. 7. **Environmental consciousness**: I aspire to be more environmentally conscious by adopting sustainable practices, reducing waste, and making eco-friendly choices in my daily life. ### ! Important - **My Book of the Year**: Pale Blue Dot by Carl Sagan - **Wishlist**: [Tomorrow, and Tomorrow, and Tomorrow](https://www.amazon.com/Tomorrow-novel-Gabrielle-Zevin/dp/0593321200), [Dell XPS-15](https://www.tokopedia.com/firstaccsupplier/laptop-dell-xps-9520-rtx3050-4gb-i7-12700-15-fhd?extParam=ivf%3Dfalse&src=topads), and a new pair of shoes. - **Song of the Year**: Alexandra by Reality Clubs

About Me

My full name is Ahsan Awadullah Azizan, but everyone calls me Ahsan. I'm currently a student at SMK Telkom Sandhy Putra Malang, diving deep into the realm of software engineering. When I'm not writing a bunch lines of code, you'll find me immersed in books, expressing my rage through gaming, and cheering on my somewhat unconventional choice of football team, Tottenham Hotspur FC. Yeah, I know, Spurs might not be everyone's first pick, but hey, where's the fun in following the crowd? Being an Indonesian through and through, I'm toying with the idea of starting a blog in Bahasa Indonesia. It just feels right to share my thoughts and experiences in the language that's closest to my heart. Stay tuned for some coding chronicles, book reviews, and perhaps a sprinkle of football fandom—Spurs style. ### Me & Programming I began my programming journey at the age of 13, inspired by [Dani](https://www.youtube.com/@Danidev). The first language I learned was C# because I was interested in game development with Unity at the time. Initially, I had very little knowledge about coding and would simply watch tutorial videos without truly understanding the concepts. This continued until I realized that I wasn't actually learning anything substantial. I came to understand that programming involves more than just watching tutorials and blindly copying code. From that point on, I made a conscious effort to learn programming properly by following a structured roadmap. I have since explored various languages such as Java, C#, and JavaScript. However, I believe that the significance lies not in the number of languages you learn, but rather in becoming proficient in a language. For me, that language is Python. I find Python particularly useful for automating repetitive tasks due to its ease of use, despite being slower compared to languages like C++, which are compiled. In conclusion, my programming journey has been shaped by the realization that effective learning goes beyond watching tutorials, and the importance of focusing on becoming proficient in a language that suits the task at hand. ### About this Website I created this website with the intention of sharing my thoughts and ideas with others, as well as having a space to store code snippets and journals. I believed that a blog would be a perfect platform for these purposes. I plan to continue updating and adding new features to the website in my free time. By the way, this website is built using the [Next.js](https://nextjs.org/) framework, with [TailwindCSS](https://tailwindcss.com/) as the CSS framework. The blog posts are written using the markdown markup language. Additionally, the website utilizes [MongoDB](https://mongodb.com/) as the database to store data. If you're interested, feel free to check out the [Github Repo](https://github.com/ahsanzizan/personal-website) for this project. Kudos to my friend [Beni](https://instagram.com/kusindr_) cuz this website are heavily inspired by his [Personal Website](https://benspace.xyz/). #### Reach Me * [Email](mailto:contact@ahsanzizan.xyz) * [Personal Website](https://ahsanzizan.xyz/) * [Instagram](https://instagram.com/ahsanzizan) * [GitHub](https://github.com/ahsanzizan) * [YouTube](https://www.youtube.com/@ahsan_azizan)