Plugin Tutorial: Custom Endpoints and Overrides
Plugins can extend or override Melon's API endpoints using
IWebApi
. This allows you to add new functionality
accessible over HTTP.
Step-by-Step Guide
1. Understanding IWebApi
IWebApi
provides methods to:
- Add middleware functions.
- Access events for API endpoints.
2. Create a Custom Endpoint
We'll add a new API endpoint: /api/myplugin/info
.
a. Implement Middleware Function
public byte[] MyPluginMiddleware(WebApiEventArgs args)
{
if (args.Api == "/api/myplugin/info")
{
var result = $"{Name}\n{Authors}\n{Version}\n{Description}";
return Encoding.UTF8.GetBytes(result);
}
// Return null to let other middlewares or the core handle the request
// If you return a response here, it will override the endpoint's original function if there is one.
return null;
}
b. Register Middleware in Execute Method
public int Execute()
{
// MyPluginMiddleware is a key that can be used
WebApi.UsePluginMiddleware(new KeyValuePair<string, Func<WebApiEventArgs, byte[]>>("MyPluginMiddleware", MyPluginMiddleware));
return 0;
}
c. Clean Up in Destroy Method
public int Destroy()
{
WebApi.RemovePluginMiddleware("MyPluginMiddleware");
return 0;
}
3. Test the Custom Endpoint
a. Rebuild and Deploy
- Rebuild your plugin.
- Copy the DLL to Melon's
Plugins
directory. - Restart Melon.
b. Use a Tool to Test the Endpoint
- Using Curl:
curl http://localhost:your_port/api/myplugin/info
4. Override Existing Endpoints
You can also override existing endpoints by handling the same API paths.
a. Handle an Existing Endpoint
public byte[] OverrideGetTrack(WebApiEventArgs args)
{
if (args.Api == "/api/track")
{
var response = "This is a custom response from MyFirstPlugin.";
return Encoding.UTF8.GetBytes(response);
}
return null;
}
b. Register the Middleware
public int Execute()
{
WebApi.UsePluginMiddleware(new KeyValuePair<string, Func<WebApiEventArgs, byte[]>>("OverrideGetTrack", OverrideGetTrack));
return 0;
}
c. Caution
- Overriding core endpoints can disrupt Melon's functionality.
- Ensure you handle requests appropriately or consider calling the original functionality after your code, rather than outright overriding the function.
5. Using API Events
Alternatively, you can subscribe to API events. While Plugin Middleware executes before a request, API Events go off right before the server response to the client.
public int Execute()
{
WebApi.GetTrack += OnGetTrack;
return 0;
}
private void OnGetTrack(object sender, WebApiEventArgs args)
{
// Add custom logic here
Console.WriteLine($"Track requested by user {args.User}");
}
7. Clean Up Events in Destroy Method
public int Destroy()
{
WebApi.GetTrack -= OnGetTrack;
WebApi.RemovePluginMiddleware("OverrideGetTrack");
return 0;
}
8. Rebuild and Test
- Rebuild your plugin.
- Deploy and restart Melon.
-
Test the overridden endpoint and observe the console output.
Last Tutorial: Managing Settings <---